package com.china_goldcard.mytoast;

import android.content.Context;
import android.media.MediaPlayer;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Created by jk on 16/10/18.
 */

public class MyToastOne extends Toast {

    /** 播放器 **/
    private MediaPlayer mPlayer;

    /** 是否播放 **/
    private boolean     isSound;

    public MyToastOne(Context context) {
        super(context);
    }

    /**
     * 构造函数-2
     * @param context
     * @param isSound
     */
    public MyToastOne(Context context, boolean isSound) {
        super (context);
        this.isSound = isSound;
        mPlayer = MediaPlayer.create (context, R.raw.toastone);
        mPlayer.setOnCompletionListener (new MediaPlayer.OnCompletionListener () {
            @Override
            public void onCompletion(MediaPlayer mp){
                mp.release ();
            }
        });
    }

    public boolean isSound() {
        return isSound;
    }

    public void setSound(boolean sound) {
        isSound = sound;
    }

    @Override
    public void show() {
        super.show();
        if (isSound){
            mPlayer.start();
        }
    }

    /**
     *
     * @param context
     * @param message
     * @param duration
     * @param isSound
     * @return
     */
    public static MyToastOne makeToast(Context context,String message,int duration,boolean isSound){
        MyToastOne toastOne = new MyToastOne(context);
        toastOne.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL,0,0);
        LayoutInflater inflate = (LayoutInflater) context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
        DisplayMetrics dm = context.getResources ().getDisplayMetrics ();
        View view = inflate.inflate (R.layout.my_toast_one, null);
        view.setMinimumWidth (dm.widthPixels);// 设置控件最小宽度为手机屏幕宽度

        TextView messageTV = (TextView) view.findViewById (R.id.toast_one_msg);
        messageTV.setText (message);

        toastOne.setView (view);

        toastOne.setDuration (duration);

        toastOne.setGravity (Gravity.CENTER_VERTICAL, 0, 0);

        return toastOne;
    }
}
